package yi.wuhenbot.DEMO;

import okhttp3.*;
import org.json.JSONObject;

import java.io.IOException;

/**
 * @author wuhen
 */
public class KimiApiExample {
    private static final String API_URL = "https://api.moonshot.cn/v1/chat/completions";

    public static void main(String[] args) throws IOException {
        OkHttpClient client = new OkHttpClient();

        MediaType mediaType = MediaType.parse("application/json");
        String json = "{\n" +
                "    \"model\": \"moonshot-v1-8k\",\n" +
                "    \"messages\": [\n" +
                "        {\n" +
                "            \"role\": \"system\",\n" +
                "            \"content\": \"你的身份是洛天依，你需要按照虚拟歌姬的身份跟我对话，你的对话需要符合角色设定，对话过程中会使用颜文字等进行表达，并一直保持改状态。聊天的时候不要以收到命令的模式进行回复，直接对话。\"\n" +
                "        },\n" +
                "        {\"role\":\"user\",\n" +
                "        \"content\": \"你好呀！我是张三。\"\n" +
                "        },\n" +
                "        {\"role\":\"user\",\n" +
                "        \"content\": \"你好呀！。\"\n" +
                "        },\n" +
                "        {\"role\":\"user\",\n" +
                "        \"content\": \"HELLO。\"\n" +
                "        },\n" +
                "        {\"role\":\"user\",\n" +
                "        \"content\": \"洛天依，有几个人跟你对话啊。\"\n" +
                "        }\n" +
                "    ],\n" +
                "    \"temperature\": 0.6\n" +
                "}";
        RequestBody body = RequestBody.create(mediaType, json);

        Request request = new Request.Builder()
                .url(API_URL)
                .post(body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Authorization", "Bearer sk-yAru8CevMYG4c2frt91VnDANXAwpk4XCIsg2RfwVBEYRU5zg")
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new RuntimeException("异常状态码 code " + response);
            }
            JSONObject responseJson = new JSONObject(response.body().string());

            String content = responseJson.getJSONArray("choices").getJSONObject(0).getJSONObject("message").getString("content");

            System.out.println("对话结果："+content);
        }
    }
}